package com.ckw.question.controller;

import com.ckw.common.pojo.State;
import com.ckw.judger.pojo.TestPack;
import com.ckw.question.config.RabbitMQConfiguration;
import com.ckw.question.utils.RedisRateLimiter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
@Slf4j
public class JudgeController {
    @Autowired
    private RabbitTemplate rabbitTemplate;

    RedisRateLimiter rateLimiter = new RedisRateLimiter();

    @PostMapping("/judge")
    public Object judgeAll(@RequestBody TestPack testPack){
        if(!rateLimiter.tryConsumeTokens(10, 5, 1)) {
            return new com.ckw.common.pojo.Message(State.FAILURE, null, "提交人数过多请稍后再试");
        }
        Object response = rabbitTemplate.convertSendAndReceive(
                RabbitMQConfiguration.JUDGE_EXCHANGE,
                RabbitMQConfiguration.JUDGE_QUEUE_ROUTING_KEY,
                testPack,
                message -> {
                    message.getMessageProperties().setReplyTo(RabbitMQConfiguration.RESPONSE_QUEUE);
                    return message;
                }
        );

        if (response != null) {
            return new com.ckw.common.pojo.Message(State.SUCCESS, response, "提交成功，判题任务已加入队列并获取到结果！");
        } else {
            return new com.ckw.common.pojo.Message(State.FAILURE, null, "提交成功，但未获取到结果");
        }
    }
}
